﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProductManager.bl;
using System.Linq;
using System.Collections;

namespace ProductManager.gui
{
    public partial class GUICompany : DevExpress.XtraEditors.XtraForm
    {
        private IEnumerable<Company> listCompany = null;
        private Company company = null;
        private ProductMDDataContext ctx = null;
        private BLCompany blCompany = null;
        private int status = 0;
        private string sname = "";

        private int currentpage = 0;
        private int totalpage = 0;
        private int pageSize = 10;

        public List<string> list= null;  

        public GUICompany()
        {
            InitializeComponent();
            RefreshData();
        }

        private void ResetText()
        {
            txtCompanyID.Text = "";
            txtCompanyName.Text = "";
            txtAddress.Text = "";
            rbtnActive.SelectedIndex = 0;
        }


        private void RefreshData()
        {
            try
            {
                status = 0;
                ctx = new ProductMDDataContext();
                var list = ctx.Companies;
                listCompany = list.AsEnumerable();
                
                LoadData();
            }
            catch (Exception ex)
            {

            }
        }


        

        private void LoadData()
        {
            try
            {
                CreatePage();
                ResetText();
                btnUpdate.Enabled = false;
                btnDelete.Enabled = false;
                btnAdd.Enabled = false;

            }
            catch (Exception ex)
            {

            }
        }

        private void LoadDataCurrent(IEnumerable<Company> data)
        {
            grvCompany.Columns.Clear();
            grvCompany.AutoGenerateColumns = false;
            grvCompany.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            DataGridViewCell cell = new DataGridViewTextBoxCell();

            DataGridViewColumn columnID = new DataGridViewColumn();
            columnID.HeaderText = "ID";
            columnID.Name = "ID";
            columnID.Visible = true;
            columnID.ReadOnly = true;
            columnID.CellTemplate = cell;
            columnID.DataPropertyName = "CompanyID";

            DataGridViewColumn columnCompanyName = new DataGridViewColumn();
            columnCompanyName.HeaderText = "Company Name";
            columnCompanyName.Name = "Company Name";
            columnCompanyName.Visible = true;
            columnCompanyName.ReadOnly = true;
            columnCompanyName.CellTemplate = cell;
            columnCompanyName.DataPropertyName = "CompanyName";

            DataGridViewColumn columnAddress = new DataGridViewColumn();
            columnAddress.HeaderText = "Address";
            columnAddress.Name = "Address";
            columnAddress.Visible = true;
            columnAddress.ReadOnly = true;
            columnAddress.CellTemplate = cell;
            columnAddress.DataPropertyName = "Address";


            DataGridViewCheckBoxColumn columnActive = new DataGridViewCheckBoxColumn();
            columnActive.HeaderText = "Active";
            columnActive.Name = "Active";
            columnActive.Visible = true;
            columnActive.ReadOnly = true;
            cell = new DataGridViewCheckBoxCell();
            columnActive.CellTemplate = cell;
            columnActive.DataPropertyName = "Status";

            grvCompany.Columns.Add(columnID);
            grvCompany.Columns.Add(columnCompanyName);
            grvCompany.Columns.Add(columnAddress);
            grvCompany.Columns.Add(columnActive);
            grvCompany.DataSource = data;
        }







        //==============================================//
        //        Pagination with sql and linq          //
        //==============================================//
        private void CreatePage()
        {
            currentpage = 0;

            if (listCompany.Count() % pageSize == 0)
            {
                totalpage = listCompany.Count() / pageSize;
            }
            else
            {
                totalpage = listCompany.Count() / pageSize + 1;
            }

            lblTotalPage.Caption = "Total page: " + totalpage.ToString();
            lblTotalCompany.Caption = "Total Company: " + listCompany.Count().ToString();


            if (totalpage != 0)
            {
                GoToPage(0);
            }
            else
            {
                grvCompany.Rows.Clear();
                barbtnFirst.Enabled = false;
                barbtnLast.Enabled = false;
                barbtnNext.Enabled = false;
                barbtnPrevious.Enabled = false;
                barbtnPreviousPage.Enabled = false;
                barbtnNextPage.Enabled = false;
            }

        }



        private void GoToPage(int page)
        {
            currentpage = page;
            if (status == 0)
            {
                LoadDataCurrent(ctx.Companies.Skip(currentpage * pageSize).Take(pageSize));
            }
            else
            {
                    var list1 = ctx.Companies.Where(c => c.CompanyName.Contains(sname)).Skip(currentpage * pageSize).Take(pageSize);
                    LoadDataCurrent(list1);
            }


            if (currentpage == 0)
            {
                barbtnFirst.Enabled = false;
                barbtnPrevious.Enabled = false;
            }
            else
            {
                barbtnFirst.Enabled = true;
                barbtnPrevious.Enabled = true;
            }

            if (currentpage == totalpage - 1)
            {
                barbtnNext.Enabled = false;
                barbtnLast.Enabled = false;
            }
            else
            {
                barbtnNext.Enabled = true;
                barbtnLast.Enabled = true;
            }

            if ((currentpage - 5) < 0)
            {
                barbtnPreviousPage.Enabled = false;
            }
            else
            {
                barbtnPreviousPage.Enabled = true;
            }

            if ((currentpage + 5) > totalpage - 1)
            {
                barbtnNextPage.Enabled = false;
            }
            else
            {
                barbtnNextPage.Enabled = true;
            }
        }

        private void grvCompany_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                DataGridViewRow row = grvCompany.Rows[e.RowIndex];
                int id = 0;
                id = Convert.ToInt32(row.Cells[0].Value.ToString());
                if (id > 0)
                {
                    company = ctx.Companies.Single(c => c.CompanyID == id);
                    txtCompanyID.Text = company.CompanyID.ToString();
                    txtCompanyName.Text = company.CompanyName;
                    txtAddress.Text = company.Address;

                    if (company.Status == true)
                    {
                        rbtnActive.SelectedIndex = 0;
                        btnDelete.Text = "Disable";
                        btnDelete.ImageIndex = 9;
                    }
                    else {
                        rbtnActive.SelectedIndex = 1;
                        btnDelete.Text = "Enable";
                        btnDelete.ImageIndex = 10;
                    }
                    btnDelete.Enabled = true;
                    btnUpdate.Enabled = true;
                    btnAdd.Enabled = false;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            ResetText();
            btnUpdate.Enabled = false;
            btnDelete.Enabled = false;
            btnAdd.Enabled = true;
        }

        private void btnList_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (blCompany.ValidateAdd(txtCompanyName.Text, txtAddress.Text))
            {
                company = new Company();
                company.CompanyName= txtCompanyName.Text;
                company.Address = txtAddress.Text;
                if (rbtnActive.SelectedIndex == 0)
                {
                    company.Status = true;
                }
                else {
                    company.Status = false;
                }

                ctx.add_Company(company.CompanyName, company.Address,company.Status);
                ctx.SubmitChanges();
                MessageBox.Show(this, "Add successful", "Add Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                RefreshData();
                list = null;
                btnAdd.Enabled = false;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(this, "Do you want to update " + company.CompanyName+ " ?", "Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                if (company!= null)
                {
                    if (blCompany.ValidateAdd(txtCompanyName.Text, txtAddress.Text))
                    {
                        company.CompanyName = txtCompanyName.Text;
                        company.Address = txtAddress.Text;
                        if (rbtnActive.SelectedIndex == 0)
                        {
                            company.Status = true;
                        }
                        else
                        {
                            company.Status = false;
                        }
                        ctx.SubmitChanges();
                    }
                }
                ctx.SubmitChanges();
                MessageBox.Show(this, "Update successful", "Update Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                RefreshData();
            }
        }

        private void GUICompany_Load(object sender, EventArgs e)
        {
            ctx = new ProductMDDataContext();
            blCompany = new BLCompany();
            txtCompanyID.Properties.ReadOnly = true;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
                if (blCompany.ValidateSearchByName(txtSearchName.Text))
                {
                    if (ctx != null)
                    {
                        status = 1;
                        sname = txtSearchName.Text;
                        var list = ctx.Companies.Where(c => c.CompanyName.Contains(sname));
                        listCompany = list.AsEnumerable();
                        LoadData();

                        if (listCompany.Count() == 0)
                        {
                            MessageBox.Show(this, "No items match your search!", "Search Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //LoadData();
                        }
                    }
                }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            string temp = btnDelete.Text.Equals("Disable") ? "Disable" : "Enable";
            DialogResult result = MessageBox.Show(this, "Do you want to "+ temp +" "+ company.CompanyName + " ?", "Change Status", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                int id = Convert.ToInt32(txtCompanyID.Text);
                if (btnDelete.Text.Equals("Disable"))
                {
                    if (ctx != null)
                    {
                        ctx.Disable_Company(id);
                        ctx.SubmitChanges();
                    }
                }
                else
                {
                    if (ctx != null)
                    {
                        ctx.Enable_Company(id);
                        ctx.SubmitChanges();
                    }
                }

                RefreshData();
            }

        }
    }
}